<template>
  <div class="blog-detail-container">
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    <div v-else-if="error" class="error">
      <i class="fas fa-exclamation-circle"></i>
      <p>{{ error }}</p>
      <button class="btn btn-primary" @click="fetchPost">重试</button>
    </div>
    <div v-else class="blog-content">
      <!-- 文章目录 -->
      <aside class="toc" v-if="toc.length > 0">
        <div class="toc-header">
          <h3>目录</h3>
        </div>
        <nav class="toc-nav">
          <ul>
            <li v-for="item in toc" 
                :key="item.id" 
                :class="['toc-item', `level-${item.level}`, { active: item.id === activeHeading }]"
                @click="scrollToHeading(item.id)">
              {{ item.text }}
            </li>
          </ul>
        </nav>
      </aside>

      <!-- 文章主体 -->
      <article class="blog-post">
        <!-- 文章头部 -->
        <header class="post-header">
          <div class="post-meta">
            <span class="category">{{ post.categoryName || '未分类' }}</span>
            <span class="date">{{ formatDate(post.createdAt) }}</span>
          </div>
          <h1 class="post-title">{{ post.title }}</h1>
          <div class="post-stats">
            <span class="stat">
              <i class="far fa-eye"></i>
              {{ post.viewCount }} 阅读
            </span>
            <span class="stat">
              <i class="far fa-heart"></i>
              {{ post.likeCount }} 喜欢
            </span>
            <span class="stat">
              <i class="far fa-comment"></i>
              {{ post.commentCount }} 评论
            </span>
          </div>
        </header>

        <!-- 文章封面 -->
        <div class="post-cover" v-if="post.coverImage">
          <img :src="post.coverImage" :alt="post.title">
        </div>

        <!-- 文章内容 -->
        <div class="post-content markdown-body" v-html="renderedContent"></div>

        <!-- 文章底部 -->
        <footer class="post-footer">
          <div class="post-tags" v-if="post.tags && post.tags.length">
            <span class="tag" v-for="tag in post.tags" :key="tag.id">
              #{{ tag.name }}
            </span>
          </div>
          <div class="post-actions">
            <button class="btn btn-like" :class="{ 'liked': isLiked }" @click="handleLike">
              <i :class="['fa-heart', isLiked ? 'fas' : 'far']"></i>
              {{ isLiked ? '已喜欢' : '喜欢' }}
            </button>
            <button class="btn btn-share" @click="handleShare">
              <i class="fas fa-share-alt"></i>
              分享
            </button>
          </div>
        </footer>
      </article>

      <!-- 广告区域 -->
      <aside class="ad-sidebar">
        <div class="ad-placeholder">
          <i class="fas fa-ad"></i>
          <p>广告位</p>
        </div>
      </aside>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { marked } from 'marked';
import DOMPurify from 'dompurify';

export default {
  name: 'BlogDetailView',
  data() {
    return {
      post: null,
      loading: true,
      error: null,
      isLiked: false,
      toc: [],
      activeHeading: null
    };
  },
  computed: {
    renderedContent() {
      if (!this.post?.content) return '';
      
      // 配置 marked 选项
      marked.setOptions({
        headerIds: true,
        headerPrefix: 'heading-'
      });
      
      const rawHtml = marked(this.post.content);
      return DOMPurify.sanitize(rawHtml);
    }
  },
  created() {
    this.fetchPost();
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    generateToc(content) {
      const tokens = marked.lexer(content);
      const toc = [];
      let idCounter = 0;

      tokens.forEach(token => {
        if (token.type === 'heading') {
          const id = `heading-${idCounter++}`;
          toc.push({
            id,
            level: token.depth,
            text: token.text
          });
        }
      });

      return toc;
    },

    scrollToHeading(id) {
      const element = document.getElementById(id);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
      }
    },

    handleScroll() {
      const headings = this.toc.map(item => document.getElementById(item.id));
      const scrollPosition = window.scrollY;

      for (let i = headings.length - 1; i >= 0; i--) {
        const heading = headings[i];
        if (heading && heading.offsetTop <= scrollPosition + 100) {
          this.activeHeading = this.toc[i].id;
          break;
        }
      }
    },

    async fetchPost() {
      this.loading = true;
      this.error = null;
      try {
        console.log('开始获取文章数据，ID:', this.$route.params.id);
        const response = await axios.get(`/api/blog/posts/${this.$route.params.id}`);
        console.log('获取到的响应数据:', response.data);
        
        if (response.data.code === 200 && response.data.data) {
          console.log('文章数据有效，设置到组件中');
          this.post = response.data.data;
          console.log('当前文章数据:', this.post);
          
          // 生成目录
          this.toc = this.generateToc(this.post.content);
          
          // 增加阅读量
          try {
            console.log('开始增加阅读量');
            await axios.post(`/api/blog/posts/${this.post.id}`);
            console.log('阅读量增加成功');
          } catch (viewError) {
            console.error('增加阅读量失败:', viewError);
          }
        } else {
          console.error('文章数据格式错误:', response.data);
          throw new Error('文章数据格式错误');
        }
      } catch (error) {
        console.error('获取文章失败，详细错误:', error);
        console.error('错误响应数据:', error.response?.data);
        console.error('错误状态码:', error.response?.status);
        this.error = error.response?.data?.message || '加载文章失败，请稍后重试';
      } finally {
        this.loading = false;
        console.log('加载状态结束，当前文章数据:', this.post);
      }
    },
    formatDate(date) {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    },
    async handleLike() {
      if (this.isLiked) return;
      try {
        await axios.post(`/api/blog/posts/${this.post.id}/like`);
        this.isLiked = true;
        this.post.likeCount++;
      } catch (error) {
        console.error('Error liking post:', error);
      }
    },
    handleShare() {
      if (navigator.share) {
        navigator.share({
          title: this.post.title,
          text: this.post.content.substring(0, 100) + '...',
          url: window.location.href
        }).catch(console.error);
      } else {
        // 复制链接到剪贴板
        navigator.clipboard.writeText(window.location.href)
          .then(() => alert('链接已复制到剪贴板'))
          .catch(console.error);
      }
    }
  }
};
</script>

<style scoped>
.blog-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.blog-content {
  display: grid;
  grid-template-columns: 240px minmax(0, 1fr) 240px;
  gap: 10px;
  max-width: 4600px;
  margin: 0 auto;

}

.toc {
  width: 240px;
  flex-shrink: 0;
  position: sticky;
  top: 20px;
  max-height: calc(100vh - 40px);
  overflow-y: auto;
  background: var(--card-bg);
  border-radius: 8px;
  padding: 20px;
  box-shadow: var(--shadow);
}

.toc-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-color);
}

.toc-header h3 {
  margin: 0;
  color: var(--heading-color);
  font-size: 1.2em;
}

.toc-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.toc-item {
  padding: 6px 0;
  cursor: pointer;
  color: var(--text-secondary);
  transition: var(--transition);
  font-size: 0.9em;
  line-height: 1.4;
}

.toc-item:hover {
  color: var(--primary-color);
}

.toc-item.active {
  color: var(--primary-color);
  font-weight: 500;
}

.level-1 { padding-left: 0; }
.level-2 { padding-left: 1em; }
.level-3 { padding-left: 2em; }
.level-4 { padding-left: 3em; }
.level-5 { padding-left: 4em; }
.level-6 { padding-left: 5em; }

.blog-post {
  flex: 1;
  background: var(--card-bg);
  border-radius: 16px;
  padding: 40px;
  box-shadow: var(--shadow);
}

.post-header {
  margin-bottom: 30px;
}

.post-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
  color: var(--text-secondary);
  font-size: 14px;
}

.category {
  background: var(--primary-color);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
}

.post-title {
  font-size: 2.5em;
  margin-bottom: 20px;
  color: var(--heading-color);
  line-height: 1.3;
}

.post-stats {
  display: flex;
  gap: 20px;
  color: var(--text-secondary);
  font-size: 14px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 5px;
}

.post-cover {
  margin: 30px -40px;
  height: 400px;
  overflow: hidden;
}

.post-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.post-content {
  margin: 40px 0;
  line-height: 1.8;
  color: var(--text-color);
}

.post-footer {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.tag {
  background: var(--secondary-color);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  transition: var(--transition);
}

.tag:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow);
}

.post-actions {
  display: flex;
  gap: 15px;
}

.btn {
  padding: 10px 20px;
  border-radius: 25px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: var(--transition);
}

.btn-like {
  background: var(--card-bg);
  color: var(--text-color);
  border: 1px solid var(--border-color);
}

.btn-like.liked {
  background: var(--accent-color);
  color: white;
  border-color: var(--accent-color);
}

.btn-share {
  background: var(--primary-color);
  color: white;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow);
}

/* Markdown 样式 */
:deep(.markdown-body) {
  color: var(--text-color);
}

:deep(.markdown-body h1),
:deep(.markdown-body h2),
:deep(.markdown-body h3),
:deep(.markdown-body h4),
:deep(.markdown-body h5),
:deep(.markdown-body h6) {
  color: var(--heading-color);
  margin-top: 2em;
  margin-bottom: 1em;
}

:deep(.markdown-body p) {
  margin-bottom: 1.5em;
}

:deep(.markdown-body ul),
:deep(.markdown-body ol) {
  margin-bottom: 1.5em;
  padding-left: 2em;
}

:deep(.markdown-body li) {
  margin-bottom: 0.5em;
}

:deep(.markdown-body code) {
  background: var(--bg-color);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 0.9em;
}

:deep(.markdown-body pre) {
  background: var(--bg-color);
  padding: 1em;
  border-radius: 8px;
  overflow-x: auto;
  margin-bottom: 1.5em;
}

:deep(.markdown-body blockquote) {
  border-left: 4px solid var(--primary-color);
  padding-left: 1em;
  margin-left: 0;
  color: var(--text-secondary);
}

.ad-sidebar {
  width: 240px;
  flex-shrink: 0;
  position: sticky;
  top: 20px;
  height: fit-content;
}

.ad-placeholder {
  background: var(--card-bg);
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  color: var(--text-secondary);
  box-shadow: var(--shadow);
}

.ad-placeholder i {
  font-size: 2em;
  margin-bottom: 10px;
}

.ad-placeholder p {
  margin: 0;
  font-size: 0.9em;
}

@media (max-width: 1400px) {
  .blog-content {
    grid-template-columns: 240px 1fr;
  }
  
  .ad-sidebar {
    display: none;
  }
}

@media (max-width: 1024px) {
  .blog-content {
    grid-template-columns: 1fr;
  }

  .toc {
    width: 100%;
    position: relative;
    top: 0;
    max-height: none;
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .blog-detail-container {
    padding: 20px;
  }

  .blog-post {
    padding: 20px;
  }

  .post-cover {
    margin: 20px -20px;
    height: 250px;
  }

  .post-title {
    font-size: 1.8em;
  }
}

@media (max-width: 480px) {
  .blog-detail-container {
    padding: 15px;
  }

  .blog-post {
    padding: 15px;
  }

  .post-cover {
    margin: 15px -15px;
    height: 200px;
  }

  .post-title {
    font-size: 1.5em;
  }
}
</style> 